from industrialai.pkg.authentication import JWT
from industrialai.pkg.page import get_page
from pecan import abort
from pecan import expose
from pecan import request
from pecan.rest import RestController
from pecan_swagger import decorators as swagger


@swagger.path("users", "User", "Root")
class UserController(RestController):

    """@api {get} /v1/users/?name=<name> get_all_users

    @apiName GetAllUsers
    @apiGroup User

    @apiParam  {String} name name of user           根据名称进行查询(使用like进行匹配)
    @apiParam  {Integer} status status of user      根据用户状态过滤
    @apiParam  {String} account account of user     根据账号进行查询(使用like进行匹配)
    @apiParam  {Integer} roleId role of user        根据角色进行过滤

    @apiSuccess (200) {Object[]} users the list of user
    @apiSuccessExample Success-Response:
    {
        "data": [
         {
             "id": 6,                                       用户id
             "number": null,                                身份证号
             "roleId": 3,                                   角色
             "status": 1,                                   状态:0/1
             "create_at": "2022-03-09 11:24:18.856936",     创建时间
             "name": "test",                                名称
             "account": "testsss1-put",                     账号
             "phone": "12345",                              手机号
             "email": null,                                 邮箱
         },
        ],
        "pages": 10                                         总页数
        “total": 10                                         总数
    }
    """
    @expose("json")
    def get(self, **kwargs):
        page_num, page_size = get_page(request.body)
        validKeys = ["enterpriseId", "name", "account", "roleId", "status"]
        kwargs = {k: v for k, v in kwargs.items() if k in validKeys}
        token = request.cookies.get("token")
        message = JWT.deToken(token)
        if message is None:
            abort(401)
        else:
            eId = message.get("enterpriseId")
            rId = message.get("roleId")
            if rId != 5:
                kwargs["enterpriseId"] = eId
        db_conn = request.db_conn
        users, pages = db_conn.list_users(page_num, page_size, **kwargs)
        return {
            "data": users,
            "pages": pages
        }

    """@api {get} /v1/users/<userId> get_one_user
       @apiName GetOneUser
       @apiGroup User

       @apiParam  {Integer} userId id of user

       @apiSuccess (200) {Object} user
       @apiSuccessExample Success-Response:
       {
            "id": 6,                                       用户id
             "number": null,                                身份证号
             "roleId": 3,                                   角色
             "status": 1,                                   状态:0/1
             "create_at": "2022-03-09 11:24:18.856936",     创建时间
             "name": "test",                                名称
             "account": "testsss1-put",                     账号
             "phone": "12345",                              手机号
             "email": null,                                 邮箱
        }
    """
    @expose("json")
    def get_one(self, user_id):
        db_conn = request.db_conn
        user = db_conn.get_user(user_id)
        user.pwd = None
        return user

    """@api {post} /v1/users create_user
       @apiName CreateUser
       @apiGroup User

       @apiBody {Object} user
       @apiParamExample {json} Request-Example:
       {
            "user": {
                "account": "testsss1-put",
                "phone": "12345",
                "email": xxx@xxxx.com,
                "name": "test",
                "pwd": "123456",
                "roleId": 3
            }
        }

       @apiSuccess {String} result
       @apiSuccessExample Success-Response:
            HTTP/1.1 200 OK

        @apiError Unauthorized
        @apiErrorExample {json} Error-Response:
            {
                "faultcode": "Client",
                "faultstring": "This server could not verify that you are
                authorized to access the document you requested. Either you
                supplied the wrong credentials (e.g., bad password), or your
                browser does not understand how to supply the credentials
                required.",
                "debuginfo": null
            }
    """
    @expose("json")
    def post(self, user):
        db_conn = request.db_conn
        db_conn.add_user(user)
        return "Success"

    """@api {put} /v1/users update_user
       @apiName UpdateUser
       @apiGroup User

       @apiBody {Object} user
       @apiParamExample {json} Request-Example:
       {
            "user": {
                "id": 6,
                "enterpriseId": 1,
                "enterpriseGroupId": 1,
                "name": "test"
            }
        }

       @apiSuccess {String} result
       @apiSuccessExample Success-Response:
            "Success"

        @apiError Unauthorized
        @apiErrorExample {json} Error-Response:
            {
                "faultcode": "Client",
                "faultstring": "This server could not verify that you are
                authorized to access the document you requested. Either you
                supplied the wrong credentials (e.g., bad password), or your
                browser does not understand how to supply the credentials
                required.",
                "debuginfo": null
            }
    """
    @expose("json")
    def put(self, user):
        token = request.cookies.get("token")
        message = JWT.deToken(token)
        if message is None:
            abort(401)
        else:
            uId = message.get("userId")
            rId = message.get("roleId")
            if uId != int(user.get("id")) and rId != 5:
                abort(401)
            elif uId == int(user.get("id")):
                user["roleId"] = None
                user["phone"] = None
        db_conn = request.db_conn
        db_conn.update_user(user)
        return "Success"
